package com.qiantu.phone.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;

import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.BuildConfig;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.ThemeUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.DeviceSettingActivity;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.RoomDeviceActivity;
import com.qiantu.phone.ui.uiutil.DeviceType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


/**
 * Created by rtyui on 2018/4/28.
 * <p>
 * 效果：ScrollView头部底部弹性
 * <p>
 * tip0:弹性尺寸为 move/2
 * <p>
 * tip1:可以双指同时拉动 这时候执行的事件 只有 一次down 一次up
 * <p>
 * tip2:可以在动画回弹时继续拉动
 * <p>
 * tip3:可以在滑动屏幕的过程中不用抬起直接拉动
 */


public abstract class HomeDeviceBaseView extends ClickFrameLayout {
    protected ShapeLinearLayout shapeLinearLayout;

    protected ImageView iconDevice;
    protected TextView tvDeviceName;
    protected TextView tvRoom;
    protected TextView tvValue;
    protected TextView tvOffline;
    protected ImageView btnDeviceOperation;

    protected DeviceBean mDevice;
    private boolean isBigView;
    private ImageView tvDeviceFlag;
    /**
     * 0 默认 1常用 2通用
     */
    private int type;

    public HomeDeviceBaseView(Context context) {
        this(context, null);
    }

    public HomeDeviceBaseView(Context context, int type) {
        super(context, null);
        this.type = type;
        initView();
    }

    public HomeDeviceBaseView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    protected abstract int getLayoutId();

    protected void isBigView(boolean isBigView){
        this.isBigView = isBigView;
    }

    protected void initView() {
        View view = LayoutInflater.from(getContext()).inflate(getLayoutId(), this, true);
        shapeLinearLayout = findViewById(R.id.view_device_back);
        iconDevice = findViewById(R.id.icon_device);
        tvDeviceName = findViewById(R.id.tv_device_name);
        tvRoom = findViewById(R.id.tv_room);
        tvValue = findViewById(R.id.tv_value);
        tvOffline = findViewById(R.id.tv_offline);
        btnDeviceOperation = findViewById(R.id.btn_device_operate);
        tvDeviceFlag = findViewById(R.id.tv_device_flag);
        if(isBigView){
            tvValue.setVisibility(GONE);
        }else{
            tvValue.setVisibility(VISIBLE);
        }
        setSwitchListener();
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if("0".equals(mDevice.getMainControlType())){
                    if(mDevice.getType().equals("curtain")){
                        Boolean isOn = mDevice.getStrokePercentage() > 50;
                        curtainOperation(isOn);
                    }else{
                        Boolean isOn = !mDevice.getIsOpen();
                        setLabelColor(isOn);
                        switchOperation(isOn);
                    }
                }else{
                    goToDetail();
                }

            }
        });
    }

    private void setSwitchListener() {
        btnDeviceOperation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToDetail();
            }
        });
    }

    protected void setLabelColor(Boolean isOn){
        String imageUrl;
        String homeSuffix = "_home";
//        if(mDevice.getMainControlType().equals("0")){
//            homeSuffix = "";
//        }
        if(mDevice.getMainControlType().equals("1")){
            imageUrl = BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + mDevice.getImageUrl() + "_on"+ homeSuffix +".png";
            shapeLinearLayout.getShapeDrawableBuilder().setGradientColors(0xFFFFFFFF,0xFFFFFFFF);
            tvDeviceName.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor1));
            tvRoom.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        }else if(isOn){
//            switch (ThemeUtil.themeId){
//                case ThemeUtil.THEME_ORANGE:
                    imageUrl = BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + mDevice.getImageUrl() + "_on"+ homeSuffix +".png";
//                    break;
//                default:
//                    imageUrl = mDevice.getOnImageUrl();
//                    break;
//            }
            shapeLinearLayout.getShapeDrawableBuilder().setGradientColors(0xFF2F4D81,0x00FFFFFF);
//            shapeLinearLayout.getShapeDrawableBuilder().setSolidColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
            tvDeviceName.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor4));
            tvRoom.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        }else{
//            switch (ThemeUtil.themeId){
//                case ThemeUtil.THEME_ORANGE:
                    imageUrl = BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + mDevice.getImageUrl() + "_off"+ homeSuffix +".png";
//                    break;
//                default:
//                    imageUrl = mDevice.getOffImageUrl();
//                    break;
//            }
            shapeLinearLayout.getShapeDrawableBuilder().setGradientColors(0xFFFFFFFF,0xFFFFFFFF);
//            shapeLinearLayout.getShapeDrawableBuilder().setSolidColor(AppApplication.getInstance().getThemeColor(R.attr.deviceSolidBgColor));
            tvDeviceName.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor1));
            tvRoom.setTextColor(AppApplication.getInstance().getThemeColor(R.attr.textColor2));
        }
        shapeLinearLayout.getShapeDrawableBuilder().intoBackground();
        GlideApp.with(iconDevice).load(imageUrl).into(iconDevice);
    }

    public void goToDetail(){
        if(mDevice.getHasControlCard() == 1){
            if(getContext() instanceof HomeActivity){
                ((HomeActivity)getContext()).showDeviceView(this, LLDeviceUtil.getDeviceDetailPage(mDevice, 1));
            }else if(getContext() instanceof RoomDeviceActivity){
                ((RoomDeviceActivity)getContext()).showDeviceView(this, LLDeviceUtil.getDeviceDetailPage(mDevice, 1));
            }
        }else{
            if(getContext() instanceof HomeActivity){
                ((HomeActivity)getContext()).showSettingView(mDevice);
            }else if(getContext() instanceof RoomDeviceActivity){
                ((RoomDeviceActivity)getContext()).showSettingView(mDevice);
            }
        }
    }

    //默认开关控制实现
    protected void switchOperation(Boolean isOn){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, isOn ? 1 : 0);
        switchOperation(option);
    }

    protected void curtainOperation(Boolean isOn){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.STROKE_PERCENTAGE, isOn ? 0 : 100);
        Map<String, Object> status = new HashMap<>();
        status.put(LLDeviceUtil.STATUS, option);
        HttpCallback<HttpData<Void>> callback =  new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
//                ToastUtils.show("执行成功");
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
    }

    protected void switchOperation(Map<String, Object> option){
        Map<String, Object> status = new HashMap<>();
        status.put(LLDeviceUtil.STATUS, option);
        HttpCallback<HttpData<Void>> callback =  new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
//                ToastUtils.show("执行成功");
                int power = (int) option.get(LLDeviceUtil.POWER);
                onSwitchOperationSucceed(power == 1);
            }

            @Override
            public void onFail(Exception e) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ToastUtils.show(R.string.exec_failure);
                }
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity) {
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        };
        if(mDevice.getDeviceGroup() == 0){
            LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }else {
            LLHttpManager.operationDeviceGroup((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, callback);
        }
    }

    protected abstract void onSwitchOperationSucceed(boolean isOpen);

    public void setDevice(DeviceBean device) {
        mDevice = device;
        updateView();
    }

    protected void updateView(){
        updateTopView();
    }

    private void updateTopView(){
        tvDeviceName.setText(mDevice.getName());
        if(mDevice.getIsOnline()){
            tvOffline.setVisibility(GONE);
            if(!isBigView){
                tvValue.setVisibility(VISIBLE);
            }
        }else{
            tvOffline.setVisibility(VISIBLE);
            if(!isBigView){
                tvValue.setVisibility(GONE);
            }
        }
        if(isBigView){
            tvDeviceFlag.setVisibility(GONE);
        }else{
            tvDeviceFlag.setVisibility(mDevice.getIsFavourite() ? VISIBLE : GONE );
        }
//        tvDeviceFlag.setVisibility(mDevice.getIsFavourite() ? VISIBLE : GONE);
        if(mDevice.getDeviceGroup() == 1){//特殊处理灯组没有不在线
            tvOffline.setVisibility(GONE);
        }
        LinearLayout.LayoutParams tvRoomLayoutParams = (LinearLayout.LayoutParams) tvRoom.getLayoutParams();
        if(type == 1){
            tvRoom.setVisibility(VISIBLE);
            tvRoomLayoutParams.rightMargin = getResources().getDimensionPixelSize(R.dimen.dp_4);
            if(mDevice.getLinkType() == 3){
                tvRoom.setText(mDevice.getFloorName());
            }else{
                tvRoom.setText(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(mDevice.getRoomSerialNo()));
            }

        }else{
            tvRoom.setText(null);
            if(isBigView){
                //需要占位
                tvRoom.setVisibility(INVISIBLE);
                tvRoomLayoutParams.rightMargin = 0;
            }else{
                tvRoom.setVisibility(GONE);
            }
        }
        setLabelColor(mDevice.getIsOpen());
    }
}
